import { t } from 'i18next'
import React from 'react'
import { IconActionOffline } from '../../../../../../components'
import { LiveModel } from '@/api/manager/live/interface'
import useLock from '@/hooks/useLock'
import { useTableLiveStore } from '../../store'
import { getItemInTree } from '../../../all/utils'
import { useTableAllStore } from '../../../all/store'
import { fetchCallOnlineMt } from '@/api/manager/actions'
import { useMccStore } from '@/pages/manager/store'
import { fetchCallMt } from '@/api/manager/actions'
import { IMcc } from '@/api/manager/type'

export type operateType = 'offline'

type ActionComponentType = Record<
	operateType,
	(mcc: LiveModel['mcc'], options: { live: LiveModel['live'] }) => React.ReactNode
>

const Offline = ({ mcc, live }: { mcc: LiveModel['mcc']; live: LiveModel['live'] }) => {
	const onClick = useLock(async () => {
		/*
            直播呼叫分情况
            需要判断 人员是否在会
            如果不在会，走addMt
            在会，判断是否在离线，如果离线，走callMt，如果在线，不做任何请求处理
        **/
		let _item: IMcc | undefined = undefined
		const tree = useTableAllStore.getState().tree
		const meetingMoid = useMccStore.getState().mccInfo.meetingMoid
		const meetingRate = useMccStore.getState().mccInfo.meetingRate
		getItemInTree(tree, ({ mcc: item }) => {
			if (item.account === mcc.account) {
				_item = item
			}
		})
		useTableLiveStore.getState().tableItemCalling(live.userCookie)
		if (_item) {
			if ((_item as IMcc).status.isOnline) {
				//不处理
			} else {
				//呼叫它
				await fetchCallOnlineMt(meetingMoid, [_item as IMcc])
			}
		} else {
			let mts = [
				{
					bitrate: meetingRate,
					meetingMoid: meetingMoid,
					accountType: mcc.accountType,
					account: mcc.account,
					name: mcc.name,
					protocol: 255,
				},
			]
			await fetchCallMt(meetingMoid, { mts })
		}
	})
	return <IconActionOffline key="offline" title={t('呼叫')} onClick={onClick} />
}
export const OperateIconComponent: ActionComponentType = {
	offline: (mcc, { live }) => <Offline mcc={mcc} live={live} />,
}
